package com.demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException
    {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 设置 RabbitMQ 地址
        factory.setHost("localhost");
        factory.setVirtualHost("/");
        // 建立到代理服务器的连接
        Connection conn = factory.newConnection();
        // 创建信道
        final Channel channel = conn.createChannel();

        // 声明交换器
        String exchangeName = "hello-exchange";
        channel.exchangeDeclare(exchangeName, "direct", true);

        // 声明队列
        String queueName = "hello";
        channel.queueDeclare(queueName,true,false,false,null);
        String routingKey = "testRoutingKey";

        // 绑定队列，通过键 testRoutingKey 将队列和交换器绑定起来
        channel.queueBind(queueName, exchangeName, routingKey);

        // 消费消息
        boolean autoAck = false;
        String consumerTag = "";
        //这是push模式  推模式
        channel.basicConsume(queueName, autoAck, consumerTag, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String routingKey = envelope.getRoutingKey();
                String contentType = properties.getContentType();
                System.out.println("消费的路由键: " + routingKey);
                System.out.println("消费的内容类型: " + contentType);
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag: " + deliveryTag);
                // 确认消息
                channel.basicAck(deliveryTag, false);
//                    channel.basicNack(deliveryTag, false, true);
                System.out.println("消费的消息内容: ");
                String bodyStr = new String(body, "UTF-8");
                System.out.println(bodyStr);
            }
        });
//        while (true) {
            //拉模式，了解即可
            //GetResponse getResponse = channel.basicGet("hello", false);
//        }
    }
}
